package cn.hiapi.shopkeeper.service.activity;

import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.jpa.activity.ActivityJpa;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author AdinZ
 * @date 2022/12/13 0:33
 */
@Service
public class ActivityService extends AbsBasicService<ActivityJpa, Activity, Long> {

    private final DispatchContext dispatchContext;

    private final String KEY = "SHOPKEEPER:ACTIVITY";

    public ActivityService(DispatchContext dispatchContext) {
        this.dispatchContext = dispatchContext;

    }

    @Override
    public Activity save(Activity activity) {
        super.save(activity);
        this.setRedis(activity);
        return activity;
    }

    @Override
    public Activity update(Activity activity) {
        return this.save(activity);
    }

    @Override
    public List<Activity> save(List<Activity> list) {


        super.save(list);
        for (Activity activity : list) {
            this.setRedis(activity);
        }
        return list;
    }

    private void setRedis(Activity activity) {
        this.redisService.set(this.KEY, activity.getId(), activity);
    }

    @Override
    public void delete(Long... longs) {
        super.delete(longs);
        for (Long id : longs) {
            this.redisService.delete(this.KEY, id);
        }
    }


    @Override
    public List<Activity> update(List<Activity> list) {
        return this.save(list);
    }

    /**
     * 活动结束
     *
     * @param list
     */
    @Transactional
    public void activityEnd(List<Activity> list) {

        list.forEach(e -> {
            e.setStatus(2);
            e.setUpdated(System.currentTimeMillis());
        });

        this.dispatchContext.getServiceList(IActivityStatusEvent.class).forEach(service -> service.activityChange(list));
        this.save(list);

    }

    /**
     * 活动开始
     *
     * @param list
     */
    @Transactional
    public void activityStart(List<Activity> list) {
        list.forEach(e -> {
            e.setStatus(1);
            e.setUpdated(System.currentTimeMillis());
        });
        this.dispatchContext.getServiceList(IActivityStatusEvent.class).forEach(service -> service.activityChange(list));
        this.save(list);
    }

    @Transactional
    public void activityUseEnd(List<Activity> list) {
        list.forEach(e -> {
            e.setUseStatus(1);
            e.setUpdated(System.currentTimeMillis());
        });
        this.dispatchContext.getServiceList(IActivityStatusEvent.class).forEach(service -> service.activityUseEnd(list));
        this.save(list);
    }
}
